package cn.young.javalearning.designpattern.proxypattern.dynamicProxy.MyProxy.impl;

import cn.young.javalearning.designpattern.proxypattern.Shopping;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;

public class MyProxy {
    public static Object newProxyInstance(MyClassLoader loader,
                                          Class<?>[] interfaces,
                                          MyInvokationHandler h) throws Exception {
        String string = "";
        String filePath = MyProxy.class.getClassLoader().getResource("").getPath();
        File file = new File(filePath + "$Proxy0.java");
        FileWriter writer = new FileWriter(file);
        writer.write(string);
        writer.flush();
        writer.close();


        //3、把生成的.java文件编译成.class文件
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager manager = javaCompiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> javaFileObjects = manager.getJavaFileObjects(file);
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, manager, null, null, null, javaFileObjects);
        task.call();
        manager.close();


        //4、编译生成的.class文件加载到JVM中来
        Class<?> proxt0 = loader.findClass("Proxt0");
        Constructor<?> constructor = proxt0.getConstructor(MyInvokationHandler.class);
        file.delete();

        return constructor.newInstance(h);
    }
}
